import React, { useState, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import axios from 'axios';

const EnergyChart = () => {
  const [currentCategory, setCurrentCategory] = useState(0);
  const [energyData, setEnergyData] = useState([]);
  const [displayData, setDisplayData] = useState([]);
  const chartRef = useRef(null);
  const myChart = useRef(null);

  const categories = [
    { name: '沪深两市', key: 'amount_hs' },
    { name: '上证', key: 'amount_sh' },
    { name: '深证', key: 'amount_sz' },
    { name: '创业板', key: 'amount_cyb' },
  ];

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('http://localhost:8001/data/market/energy/');
        // console.log("response.data.energy = :", response.data.energy);
        const data = Array.isArray(response.data.energy) ? response.data.energy : [];
        console.log("获取市场量能数据:", data);
        setEnergyData(data);
        // 默认显示全部数据
        setDisplayData(data);
      } catch (error) {
        console.error('获取市场量能数据失败:', error);
        setEnergyData([]);
        setDisplayData([]);
      }
    };
    const initChart = () => {
      if (chartRef.current) {
        myChart.current = echarts.init(chartRef.current);
        // 强制触发resize事件，确保图表正确填充容器
        setTimeout(() => {
          if (myChart.current && !myChart.current.isDisposed()) {
            myChart.current.resize({
              width: chartRef.current.clientWidth,
              height: chartRef.current.clientHeight
            });
          }
        }, 0);
      }
    };

    fetchData().then(() => {
      initChart();
      // 再次触发resize，确保图表填充容器
      setTimeout(() => {
        if (myChart.current && !myChart.current.isDisposed()) {
          myChart.current.resize({
            width: chartRef.current.clientWidth,
            height: chartRef.current.clientHeight
          });
        }
      }, 100);
    });
  }, []);

  useEffect(() => {
    if (energyData.length === 0 || !chartRef.current) return;

    // 检查实例是否已销毁或未初始化
    if (!myChart.current || myChart.current.isDisposed()) {
      myChart.current = echarts.init(chartRef.current);
    }

    // 根据当前选择的市场类型获取对应的数据key
    const currentKey = categories[currentCategory].key;
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: params => {
          return params.value;
        },
        backgroundColor: 'transparent',
        borderWidth: 0,
        textStyle: {
          color: '#333',
          fontSize: 12
        }
      },
      grid: {
        top: '5%',
        left: '3%',
        right: '4%',
        bottom: '2%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: displayData.map(item => item.trade_date),
        // boundaryGap: false,
        axisLabel: {
          show: true,
          formatter: (value, index) => {
            // 只在最后一个位置显示日期
            return index === displayData.length - 1 ? value : '';
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '量能',
      },
      series: [
        {
          name: categories[currentCategory].name,
          data: displayData.map(item => item[categories[currentCategory].key]),
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: function(params) {
              const index = params.dataIndex;
              if (index === 0) return '#52c41a';
              const currentValue = displayData[index][categories[currentCategory].key];
              const prevValue = displayData[index - 1][categories[currentCategory].key];
              return currentValue > prevValue ? '#ff4d4f' : '#52c41a';
            },
          },
        },
      ],
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100,
        },
      ],
    };

    myChart.current.setOption(option);
    
    // 强制触发resize事件，确保图表正确填充容器
    // setTimeout(() => {
    //   if (myChart.current && !myChart.current.isDisposed()) {
    //     myChart.current.resize({
    //       width: chartRef.current.clientWidth,
    //       height: chartRef.current.clientHeight
    //     });
    //   }
    // }, 0);
    console.log('data changed!')
    // 处理窗口大小变化
    const handleResize = () => {
      myChart.current?.resize();
    };
    handleResize();
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.current?.dispose();
    };
  }, [energyData, displayData, currentCategory]);

  // 计算当前类别的量能数值
  const currentValue = displayData.length > 0 
    ? displayData[displayData.length - 1][categories[currentCategory].key]
    : 0;

  return (
    <div className="chart-container mini-chart" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        height: '10%', 
        padding: '0 8px'
      }}>
        <h3 style={{ margin: 0, fontSize: '16px', fontWeight: 'bold', position: 'absolute', left: '50%', transform: 'translateX(-50%)' }}>
          市场量能{displayData.length > 0 ? `  (${displayData[displayData.length - 1].trade_date})` : ''}
        </h3>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <span style={{ fontSize: '14px' }}>{categories[currentCategory].name}: {currentValue.toFixed(1)}亿元</span>
          <button
            onClick={() => setCurrentCategory((prev) => (prev + 1) % categories.length)}
            style={{ 
              background: 'none', 
              border: 'none', 
              cursor: 'pointer',
              color: '#1890ff',
              fontSize: '16px',
              display: 'flex',
              flexDirection: 'column'
            }}
          >
            <span>↔</span>
          </button>
        </div>
      </div>
      <div 
        ref={chartRef} 
        style={{ width: '100%', height: '80%' }} 
      />
    </div>
  );
};

export default EnergyChart;